package com.android.functionmanagement.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;

import com.android.functionmanagement.globle.ConstantGloble;
import com.android.functionmanagement.globle.LogGloble;
import com.android.functionmanagement.util.DeviceUtils;
import com.android.functionmanagement.util.SharedPreferencesUtils;
import com.android.functionmanagement.util.StepOpenHelper;
import com.codoon.unova.util.Constants;

public class PedometerService extends Service {

	private static final String TAG = "fu_step";
	private static final long STEP_SAVE_MILLIS_GAP = 1*60*1000;
	private static final int sensorTypeC = Sensor.TYPE_STEP_COUNTER;
	private static final int MSG_SAVE_REBOOT = 1001;
	private static final int MSG_SAVE_FOR_DATE = 1002;
	private static final int MSG_SAVE_FOR_TODAY = 1003;
	private static final int MSG_REQUEST_TODAY_STEP_CODOON = 1004;
	private static final int STEP_HASH_MAPS = 60;
	private SensorManager mSensorManager;
	private Sensor mStepCount;
	private int mCount;// 步行总数
	private long mLastTimeMillis = 0;
	private StepOpenHelper mOpenHelper;
	private static Context mContext;

	private SensorEventListener sensorLisener = new SensorEventListener() {

		@Override
		public void onSensorChanged(SensorEvent event) {
			mCount = (int) event.values[0];
			long currMillis = SystemClock.elapsedRealtime();
			if (Math.abs(currMillis - mLastTimeMillis) >= STEP_SAVE_MILLIS_GAP) {
				mLastTimeMillis = currMillis;
				int currSteps = getCurrentSteps();
				int stepBufferCount = 0;
				if (currSteps > 0) {
					mOpenHelper.insertStepBuffer(currSteps,System.currentTimeMillis());
					stepBufferCount = mOpenHelper.getStepBufferCount();
					LogGloble.d(TAG, " =onSensorChanged=curSteps: " + currSteps  + "==stepLine:"+stepBufferCount);
				}
				if(stepBufferCount > STEP_HASH_MAPS){
					Message msg = mHandler.obtainMessage();
					msg.what = MSG_SAVE_FOR_TODAY;
					msg.sendToTarget();
				}
			}
		}

		@Override
		public void onAccuracyChanged(Sensor sensor, int accuracy) {
			// TODO Auto-generated method stub

		}
	};

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		Log.e(TAG, " onStartCommand ");
		mSensorManager = (SensorManager) this.getSystemService(Context.SENSOR_SERVICE);
		mStepCount = mSensorManager.getDefaultSensor(sensorTypeC);
		mSensorManager.registerListener(sensorLisener, mStepCount, SensorManager.SENSOR_DELAY_FASTEST);
		mContext = this;
		mOpenHelper = StepOpenHelper.getInstance(mContext);
		IntentFilter filter = new IntentFilter();
		filter.addAction("android.intent.action.PEDOMETER_SAVE_STEPS");
		filter.addAction("android.intent.action.PEDOMETER_DATE_CHANGE");
		filter.addAction("android.intent.action.UPDATE_TODAY_STEP");
		filter.addAction(Constants.ACTION_REQUEST_TODAY_STEP_CODOON);
		mContext.registerReceiver(mReceiver, filter);
		return super.onStartCommand(intent, flags, startId);
	}
	
	private BroadcastReceiver mReceiver = new BroadcastReceiver(){
		public void onReceive(Context context, Intent intent) {
			Log.e(TAG, " mReceiver action = " + intent.getAction());
			if("android.intent.action.PEDOMETER_SAVE_STEPS".equals(intent.getAction())) {
				Message msg = mHandler.obtainMessage();
				msg.what = MSG_SAVE_REBOOT;
				msg.sendToTarget();
			} else if("android.intent.action.UPDATE_TODAY_STEP".equals(intent.getAction())) {
				Message msg = mHandler.obtainMessage();
				msg.what = MSG_SAVE_FOR_TODAY;
				msg.sendToTarget();
			} else if("android.intent.action.PEDOMETER_DATE_CHANGE".equals(intent.getAction())) {
				Message msg = mHandler.obtainMessage();
				msg.what = MSG_SAVE_FOR_DATE;
				msg.sendToTarget();
			} else if(Constants.ACTION_REQUEST_TODAY_STEP_CODOON.equals(intent.getAction())) {
				Message msg = mHandler.obtainMessage();
				msg.what = MSG_REQUEST_TODAY_STEP_CODOON;
				msg.sendToTarget();
			}
		};
	};

	@Override
	public void onDestroy() {
		super.onDestroy();
		mSensorManager.unregisterListener(sensorLisener);
		unregisterReceiver(mReceiver);
	}

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			int lastSteps = (Integer) SharedPreferencesUtils.getParam(mContext, ConstantGloble.STEP_LAST_STEP, 0);
			String todayTime = (String) SharedPreferencesUtils.getParam(mContext, ConstantGloble.STEP_TODAY_TIME, "");
			String currentDate = getCurrentDate();
			int todaySteps = 0;
			
			switch (msg.what) {
			case MSG_SAVE_FOR_DATE:// 日期改变
				if (todayTime.equals(getDate())) {
					todaySteps = (Integer) SharedPreferencesUtils.getParam(mContext, ConstantGloble.STEP_TODAY_STEP, 0);
				}
				if (todayTime.equals(currentDate)) {
					LogGloble.d(TAG, " =change_date_a=mCount: " + mCount + "==lastSteps: " + lastSteps + "==todaySteps:" + todaySteps);
					return;
				}
				if (mCount == 0)lastSteps = 0;
				int _currSteps1 = mCount - lastSteps + todaySteps;
				LogGloble.d(TAG, " =change_date=mCount: " + mCount + "==lastSteps: " + lastSteps + "==todaySteps:" + todaySteps + "==currSteps:" + _currSteps1);
				
				mOpenHelper.update(_currSteps1, getDate()); // 保存前一天步数
				
				SharedPreferencesUtils.setParam(mContext, ConstantGloble.STEP_TODAY_STEP, 0);
				SharedPreferencesUtils.setParam(mContext, ConstantGloble.STEP_LAST_STEP, mCount);
				SharedPreferencesUtils.setParam(mContext, ConstantGloble.STEP_TODAY_TIME, currentDate);
				break;
			case MSG_SAVE_REBOOT:
				if (todayTime.equals(currentDate)) {
					todaySteps = (Integer) SharedPreferencesUtils.getParam(mContext, ConstantGloble.STEP_TODAY_STEP, 0);
				}
				if (mCount == 0)lastSteps = 0;
				int _currSteps2 = mCount - lastSteps + todaySteps;
				LogGloble.d(TAG, " =2=reboot_save=mCount: " + mCount + "==lastSteps: " + lastSteps + "==todaySteps:" + todaySteps + "==currSteps:" + _currSteps2);
				
				mOpenHelper.update(_currSteps2, currentDate);
				
				SharedPreferencesUtils.setParam(mContext, ConstantGloble.STEP_TODAY_STEP, _currSteps2);
				SharedPreferencesUtils.setParam(mContext, ConstantGloble.STEP_LAST_STEP, 0);
				SharedPreferencesUtils.setParam(mContext, ConstantGloble.STEP_TODAY_TIME, currentDate);
				break;
			case MSG_SAVE_FOR_TODAY: //update today upload_server
				int _currSteps3 = getCurrentSteps();
				LogGloble.d(TAG, " =3=upload_server=mCount: " + mCount  + "==currSteps:" + _currSteps3);
				DeviceUtils.uploadData(mContext, ConstantGloble.UPLOAD_TYPE_OF_STEP, 0);
				break;
			case MSG_REQUEST_TODAY_STEP_CODOON:// update today codoon
				if (todayTime.equals(currentDate)) {
					todaySteps = (Integer) SharedPreferencesUtils.getParam(mContext, ConstantGloble.STEP_TODAY_STEP, 0);
				}
				if (mCount == 0)lastSteps = 0;
				int _currSteps4 = mCount - lastSteps + todaySteps;  
				LogGloble.d(TAG, " =4=request_codoon=mCount: " + mCount + "==lastSteps: " + lastSteps + "==todaySteps:" + todaySteps + "==currSteps:" + _currSteps4);

				mOpenHelper.update(_currSteps4, currentDate);
				DeviceUtils.uploadData(mContext, ConstantGloble.UPLOAD_TYPE_OF_STEP, 0);
				
				SharedPreferencesUtils.setParam(mContext, ConstantGloble.STEP_TODAY_STEP, _currSteps4);
				SharedPreferencesUtils.setParam(mContext, ConstantGloble.STEP_LAST_STEP, mCount);
				SharedPreferencesUtils.setParam(mContext, ConstantGloble.STEP_TODAY_TIME, currentDate);

				Intent _intent = new Intent(Constants.ACTION_RESPONSE_TODAY_STEP_CODOON);
				_intent.putExtra(Constants.TODAY_CODOON_STEPS, _currSteps4);
				mContext.sendBroadcast(_intent);
				break;
			}
		}

	};

	private int getCurrentSteps() {
		int todaySteps = 0;
		int lastSteps = (Integer) SharedPreferencesUtils.getParam(mContext, ConstantGloble.STEP_LAST_STEP, 0);
		String todayTime = (String) SharedPreferencesUtils.getParam(mContext, ConstantGloble.STEP_TODAY_TIME, "");
		String currentDate = getCurrentDate();
		
		if (todayTime.equals(currentDate)) {
				todaySteps = (Integer) SharedPreferencesUtils.getParam(mContext, ConstantGloble.STEP_TODAY_STEP, 0);
		}
		
		if (mCount == 0)lastSteps = 0;
		int _currSteps3 = mCount - lastSteps + todaySteps;		
		mOpenHelper.update(_currSteps3, currentDate);
		
		SharedPreferencesUtils.setParam(mContext, ConstantGloble.STEP_TODAY_STEP, _currSteps3);
		SharedPreferencesUtils.setParam(mContext, ConstantGloble.STEP_LAST_STEP, mCount);
		SharedPreferencesUtils.setParam(mContext, ConstantGloble.STEP_TODAY_TIME, currentDate);
		
		return _currSteps3;
	}

	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

	public String getDate() {
		return df.format(new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000));// 获取的是上一天的时间
	}

	public String getCurrentDate() {
		return df.format(System.currentTimeMillis());
	}
}
